package com.example.demo.http.controllers.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.demo.models.Activity;
import com.example.demo.models.ActivityUser;
import com.example.demo.models.user.User;
import com.example.demo.services.ActivityUserService;
import com.example.demo.services.system.ResultService;
import com.example.demo.services.system.UserService;
import gaarason.database.appointment.Paginate;
import gaarason.database.contract.eloquent.Builder;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.exception.EntityNotFoundException;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/admin/activity/")
public class ActivityController {
    @Resource
    Activity.Model activityModel;
    @Resource
    ActivityUser.Model activityUserModel;

    //查询所有活动
    @GetMapping("/")
    ResultService.Result index(@RequestParam Map<String, String> params) {
        //分页单独处理
        String page = params.get("page");
        if (Objects.isNull(page)) {
            //如果没有页数，默认为第一页
            page = "1";
        }
        //生成查询器
        //查询限制只查询开放的活动
        Builder<Activity, Long> builder = activityModel.newQuery();
        //放入参数
        params.forEach((key, value) -> {
            if (!Objects.isNull(key) && !key.equals("page")) {
                //要去掉page这个参数，如果还要去掉其他就直接在这里加
                if (!Objects.isNull(value)) {
                    builder.where(key, value);
                }
            }
        });
        //返回结果
        Paginate<Activity> paginate = builder.paginate(page, 16);
        //对结果进行处理
        Map<String, Object> data = new HashMap<>();
        data.put("currentPage", paginate.getCurrentPage());
        data.put("lastPage", paginate.getLastPage());
        data.put("total", paginate.getTotal());
        data.put("perPage", paginate.getPerPage());
        data.put("data", paginate.getItemList());
        ResultService.Result result = ResultService.getNormalResult();
        result.data = data;
        return result;
    }

    //查询单个活动
    @GetMapping("/item")
    ResultService.Result item(@RequestParam Map<String, String> params) {
        //返回值
        ResultService.Result result = ResultService.getNormalResult();
        Record<Activity, Long> activity;
        if (Objects.isNull(params.get("id"))) {
            //活动不存在
            result.code = ResultService.NOT_FOUND;
            result.msg = "活动不存在";
            return result;
        } else {
            try {
                activity = activityModel.newQuery().findOrFail(params.get("id"));
            } catch (EntityNotFoundException e) {
                //找不到活动
                result.code = ResultService.NOT_FOUND;
                result.msg = "活动不存在";
                return result;
            }
            //当前用户
            User user = UserService.getThreadInstance().getUser();
            if (activity.getEntity().getIsOpen().equals(1)) {
                //如果活动开放了
            } else if (activity.getEntity().getNumber().equals(user.getNumber())) {
                //或者创建者就是当前的管理员，那么可以正常执行
            } else {
                //否则假装找不到活动
                result.code = ResultService.NOT_FOUND;
                result.msg = "活动不存在";
                return result;
            }
            //正常返回结果
            result.data = activity.getEntity();
        }
        return result;
    }

    //导出活动记录
    @GetMapping("/exportExcel")
    public void exportExcel(@RequestParam Map<String, String> params) throws IOException {
        ResultService.Result result = ResultService.getNormalResult();
        Record<ActivityUser, Long> activityUser;
        Record<Activity, Long> activity;  // 获取活动标题
        if (!Objects.isNull(params.get("id"))) {
            try {
                activityUser = activityUserModel.newQuery().findOrFail(params.get("id"));
                activity = activityModel.newQuery().findOrFail(params.get("id"));
                ActivityUserService.exportExcel(activity.getEntity().getTitle(), activityUser, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse());
            } catch (EntityNotFoundException e) {
                //找不到就报错
                result.code = ResultService.NOT_FOUND;
                result.msg = "id not found";
            }
        }
    }
}
